/*
 * @Author: GL
 * @Date: 2023-01-03 18:37:49
 * @LastEditors: GL
 * @LastEditTime: 2023-01-06 14:38:13
 * @Description: 支付
 */

const WxPay = require('wechatpay-node-v3');
const fs = require('fs');

// 创建支付实例
const pay = new WxPay({
  appid: 'wx900cf030602b5fee',
  mchid: '1636809977',
  publicKey: fs.readFileSync('./router_handler/apiclient_cert.pem',(err, data) => {
    if (err) throw err;
    console.log(data);
  }), // 公钥
  privateKey: fs.readFileSync('./router_handler/apiclient_key.pem',(err, data) => {
    if (err) throw err;
    console.log(data);
  }), // 秘钥
});

// 预支付订单信息
exports.payInfo = (req,res) => {
  // 接收前端传过来的openid
  console.log(req.body.openid);
  let openid = req.body.openid;
  const params = {
      description: '用户支付费用，完成交易', // 订单描述
      out_trade_no: randomNumber(), // 订单号，一般每次发起支付都要不一样，可使用随机数生成
      notify_url: 'https://pay.lipux.cn/notify_url',
      amount: {
          total: 1, // 支付金额，单位为分
      },
      payer: {
          openid: openid, // 微信小程序用户的openid，一般需要前端发送过来
      },
      scene_info: {
          payer_client_ip: 'ip', // 支付者ip，这个不用理会也没有问题
      },
  };
  pay.transactions_jsapi(params).then(r => {
    res.send(r);
  })
  // 将结果响应给微信小程序前端
  
}

// 订单号生成函数
function randomNumber() {
  const now = new Date()
  let month = now.getMonth() + 1
  let day = now.getDate()
  let hour = now.getHours()
  let minutes = now.getMinutes()
  let seconds = now.getSeconds()
  month = month < 10 ? "0" + month : month;
  day = day < 10 ? "0" + day : day;
  hour = hour < 10 ? "0" + hour : hour;
  minutes = minutes < 10 ? "0" + minutes : minutes;
  seconds = seconds < 10 ? "0" + seconds : seconds;
  let orderCode = now.getFullYear().toString() + month.toString() + day + hour + minutes + seconds + (Math.round(Math.random() * 1000000)).toString();
  return orderCode;
}
